<template>
  <div class="container">
    <div class="tab">
      <el-tabs v-model="selectTab" class="demo-tabs">
        <el-tab-pane label="遗失物品" name="lost">
        </el-tab-pane>
        <el-tab-pane label="拾取物品" name="pick">
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 遗失物品 -->
    <layout-card v-if="selectTab === 'lost'" :filters="exampleOptions" headline="信息列表" @search-change="searchChange"
      @search-reset="searchReset">

      <InfoList @click="showDetail" :tableData="tableData" :loading="loading" selectTab="lost" />

      <div>
        <TablePagination :small="false" :pagination="pager" @current-change="currentChange" @size-change="sizeChange" />
      </div>
    </layout-card>

    <!-- 拾取物品 -->
    <layout-card v-if="selectTab === 'pick'" :filters="exampleOptions2" headline="信息列表" @search-change="searchChange"
      @search-reset="searchReset">

      <InfoList @click="showDetail" :tableData="tableData" :loading="loading" selectTab="pick" />

      <div>
        <TablePagination :small="false" :pagination="pager" @current-change="currentChange" @size-change="sizeChange" />
      </div>
    </layout-card>

    <GoodsRecycleDetail :selectTab="selectTab" :visible="detailVisible" :info="detailInfo" @ok="cancelDetail"
      @cancel="cancelDetail" />
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onBeforeMount, watch, computed } from 'vue';
import LayoutCard from '@/components/LayoutCard/index.vue';
import { getResource } from '@/api/resource'
import { goodsTypeList } from '@/api/lose/goodsType'
import {
  getGoodsLostList,
  getGoodsRecycleList,
  getGoodsLostDetail,
  getGoodsRecycleDetail,
} from '@/api/lose/goodsRecycle/goodsRecycle';
import { ElMessage } from 'element-plus'
import TablePagination from '@/components/TablePagination/index.vue'
import InfoList from './infoList';
import GoodsRecycleDetail from './detail.vue';
import _ from 'lodash';
import moment from 'moment';

interface SearchType { }

const selectTab = ref('lost')
const loading = ref(false)
const tableData = ref<any[]>([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const exampleOptions = ref([
  {
    label: '物品类型',
    prop: 'goodsType',
    type: 'select',
    defaultValue: '',
    inputProps: {
      options: [
        { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '物品名称',
    prop: 'goodsName',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入物品名称'
    }
  },
  {
    label: '失主姓名',
    prop: 'lostName',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入失主姓名'
    }
  },
  {
    label: '遗失地',
    prop: 'lostPlace',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入遗失地'
    }
  },
  {
    label: '航站楼',
    prop: 'lostTerminal',
    type: 'checkbox',
    defaultValue: [''],
    inputProps: {
      options: [
        { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '遗失时间',
    prop: 'time',
    type: 'datePicker',
    defaultValue: [],
    inputProps: {
      type: 'daterange',
      'value-format': 'YYYY-MM-DD HH:ss:mm',
       "start-placeholder":"YYYYMMDD HH:MM",
        "end-placeholder":"YYYYMMDD HH:MM",
    }
  },
  {
    label: '处置时间',
    prop: 'lastMenderTime',
    type: 'datePicker',
    defaultValue: [],
    inputProps: {
      type: 'daterange',
      'value-format': 'YYYY-MM-DD HH:ss:mm',
       "start-placeholder":"YYYYMMDD HH:MM",
        "end-placeholder":"YYYYMMDD HH:MM",
    }
  },
])


const exampleOptions2 = ref([
  {
    label: '物品类型',
    prop: 'goodsType',
    type: 'select',
    defaultValue: '',
    inputProps: {
      options: [
        // { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '物品名称',
    prop: 'goodsName',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入物品名称'
    }
  },
  {
    label: '物品编号',
    prop: 'goodsCode',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入物品编号'
    }
  },
  {
    label: '捡拾人姓名',
    prop: 'pickUpName',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入捡拾人姓名'
    }
  },
  {
    label: '捡拾地',
    prop: 'pickUpPlace',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入捡拾地'
    }
  },
  {
    label: '航站楼',
    prop: 'storeTerminal',
    type: 'checkbox',
    defaultValue: [''],
    inputProps: {
      showCheckAll: true,
      options: [
        // { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '捡拾时间',
    prop: 'time',
    type: 'datePicker',
    defaultValue: [],
    inputProps: {
      type: 'daterange',
      'value-format': 'YYYY-MM-DD HH:ss:mm',
       "start-placeholder":"YYYYMMDD HH:MM",
        "end-placeholder":"YYYYMMDD HH:MM",
    }
  },
  {
    label: '存放位置',
    prop: 'depositPlace',
    type: 'select',
    defaultValue: [],
    inputProps: {
      // 控制是否显示权限功能
      clearable: true,
      placeholder: '请选择存放位置',
      options: [
      ]
    }
  },
  // {
  //   label: '处置时间',
  //   prop: 'lastMenderTime',
  //   type: 'datePicker',
  //   defaultValue: [],
  //   inputProps: {
  //     type: 'daterange',
  //     'value-format': 'YYYY-MM-DD HH:ss:mm'
  //   }
  // },
])
const search = ref<SearchType>({})

const detailVisible = ref(false);
const detailInfo = ref(null);

/**
* 点击查询
*/
const searchChange = (data: FilterDataType) => {
  search.value = data
  loadData()
}

/**
* 点击重置
* @param data 数据
*/
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  loadData()
}

// 修改分页
const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}

const loadData = async () => {
  loading.value = true;
  tableData.value = [];

  // 先保存分页数据
  const payload: any = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
    }
  }
  if (search.value?.goodsName) payload.condition.goodsName = search.value?.goodsName;
  if (search.value?.depositPlace) payload.condition.depositPlace = search.value?.depositPlace?.filter(item => item).join(',');
  if (search.value?.goodsCode) payload.condition.goodsCode = search.value?.goodsCode;
  if (search.value?.lostName) payload.condition.lostName = search.value?.lostName;
  if (search.value?.lostPlace) payload.condition.lostPlace = search.value?.lostPlace;
  if (search.value?.lostTerminal?.filter(item => item)?.[0]) payload.condition.lostTerminal = search.value?.lostTerminal?.filter(item => item)?.[0];

  if (search.value?.pickUpName) payload.condition.pickUpName = search.value?.pickUpName;
  if (search.value?.pickUpPlace) payload.condition.pickUpPlace = search.value?.pickUpPlace;
  if (search.value?.storeTerminal) payload.condition.storeTerminal = search.value?.storeTerminal?.filter(item => item).join(',');

  // 遗失时间范围
  if (search.value.time && search.value.time?.length > 0) {
    payload.condition.startTime = search.value.time[0] || '';
    payload.condition.endTime = search.value.time[1] || '';
  }

  // 处置时间范围
  if (search.value.lastMenderTime && search.value.lastMenderTime?.length > 0) {
    payload.condition.startLastMenderTime = search.value.lastMenderTime[0] || '';
    payload.condition.endLastMenderTime = search.value.lastMenderTime[1] || '';
  }

  // 物品类型
  if (search.value.goodsType) {
    payload.condition.goodsType = search.value.goodsType || '';
  }

  let fetch = getGoodsRecycleList;
  if (selectTab.value === 'lost') {
    // 遗失
    fetch = getGoodsLostList
    // sign1 =status1 和 3（寻找中、过期）  
    // sign2 = status2 （已找回）
    // status4（回收站）

    payload.condition.status = "4"; // 1
  } else {
    // 拾取
    payload.taskProcess = '已回收';
  }

  // ...获取数据
  const res: any = await fetch(payload);
  loading.value = false
  if (res && res.code === '1') {
    const data = res?.data?.list.map((item: any) => {
      try {
        item.nodeContentObj = JSON.parse(item.nodeContent)
      } catch (error) {
        console.error(error)
      }
      try {
        item.taskContentObj = JSON.parse(item.taskContent)
      } catch (error) {
        console.error(error)
      }
      let goodsType = '';
      if (item.goodsType) exampleOptions.value.forEach(item2 => {
        // 物品类型
        if (item2.prop === 'goodsType') {
          item2.inputProps.options?.forEach(ele => {
            if (ele.value === item.goodsType) {
              goodsType = ele.label;
            }
          })
        }
      })
      item.goodsType = goodsType
      return item
    })
    pager.total = res?.data?.total
    tableData.value = _.sortBy(data, (item: any) => moment(_.get(item, 'lastUpdateTime')).valueOf())
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

// 加载物品类型
const queryGoodsTypeList = () => {
  goodsTypeList({}).then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        const { data } = res
        exampleOptions.value.forEach(item => {
          // 物品类型
          if (item.prop === 'goodsType') {
            item.inputProps.options = [
              { label: '全部', value: '' },
              ...data.map((item: any) => ({
                label: item.goodsType,
                value: item.typeId,
              }))
            ]
          }
        })
        exampleOptions2.value.forEach(item => {
          // 物品类型
          if (item.prop === 'goodsType') {
            item.inputProps.options = [
              { label: '全部', value: '' },
              ...data.map((item: any) => ({
                label: item.goodsType,
                value: item.typeId,
              }))
            ]
          }
        })
      }
    }

    // 分页查询
    loadData()
  })
}

// 加载航站楼数据字典
const loadDict = () => {
  getResource('terminal').then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        let list = res.data?.properties?.meta || []
        exampleOptions.value.forEach(item => {
          // 航站楼
          if (item.prop === 'lostTerminal') {
            item.inputProps.options = [
              // { label: '全部', value: '' },
              ...list
            ]
          }
        })
        exampleOptions2.value.forEach(item => {
          // 航站楼
          if (item.prop === 'storeTerminal') {
            item.inputProps.options = [
              // { label: '全部', value: '' },
              ...list
            ]
          }
        })
      }
    }
  })
  getResource('lose_deposit_place').then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        let list = res.data?.properties?.meta || []
        exampleOptions2.value.forEach(item => {
          // 存放位置
          if (item.prop === 'depositPlace') {
            item.inputProps.options = [
              { label: '全部', value: '' },
              ...list
            ]
          }
        })
      }
    }
  })
}

// 显示详情
const showDetail = (record) => {
  detailInfo.value = record;
  detailVisible.value = true;
}

// 隐藏详情
const cancelDetail = () => {
  detailInfo.value = null;
  detailVisible.value = false;
}

onBeforeMount(() => {

  // 加载航站楼数据字典
  loadDict();

  // 加载物品类型
  queryGoodsTypeList();


})

// 切换tab 初始化分页，并重新获取接口
watch(() => selectTab.value, (val) => {
  pager.currentPage = 1;
  loadData();
})

</script>

<style lang="less" scoped>
.container {
  background: #f5f7f9;

  .tab {
    padding: 12px 24px;
    margin: 12px 12px 0px 12px;
    background: #FFF;
    border-radius: 8px;
  }
}
</style>